package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.RepairPassword;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private HttpSession session;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password){
        try {
            //获取主体
            Subject subject = SecurityUtils.getSubject();
            //创建令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username,RepairPassword.getPasswordHeighten(username, password));
            //使用主体调用登录功能
            subject.login(token);
        } catch(UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult("账号不存在",false);
        }catch (IncorrectCredentialsException e){
            return new JsonResult("密码错误",false);
        }catch (LogicException e){
            e.printStackTrace();
            return new JsonResult(e.getMessage(),false);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("请联系管理员",false);
        }
      return new JsonResult();
    }


    @RequestMapping("/errorForward")
    public String errorForward(){
        return "common/nopermission";
    }

    @RequestMapping("/benOrRecover")
    @ResponseBody
    public JsonResult benOrRecover(Long id,boolean status){
        employeeService.updateStatus(id,status);
        return new JsonResult();
    }
}
